package com.qujia.fleet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.fleet.domain.FleetCard;
import com.qujia.fleet.domain.FleetCardAllocationRecoveryRecord;
import com.qujia.fleet.domain.FleetCardSub;
import com.qujia.fleet.domain.form.FleetCardSubAddForm;
import com.qujia.fleet.domain.form.FleetCardSubForm;
import com.qujia.fleet.domain.form.FleetCardSubQueryForm;
import com.qujia.fleet.domain.vo.FleetCardSubVo;
import com.qujia.fleet.mapper.FleetCardMapper;
import com.qujia.fleet.mapper.FleetCardSubMapper;
import com.qujia.fleet.service.FleetCardAllocationRecoveryRecordService;
import com.qujia.fleet.service.FleetCardService;
import com.qujia.fleet.service.FleetCardSubService;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.domain.SysAppUserInfo;
import com.qujia.station.domain.vo.EnterpriseAndStationVo;
import com.qujia.station.mapper.AppUserInfoMapper;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.IStationService;
import com.qujia.station.utils.RegexUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class FleetCardSubServiceImpl implements FleetCardSubService {

    @Autowired
    private FleetCardSubMapper fleetCardSubMapper;

    @Autowired
    private AppUserInfoMapper appUserInfoMapper;

    @Autowired
    private FleetCardService fleetCardService;

    @Autowired
    private FleetCardMapper fleetCardMapper;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IStationService stationService;

    @Autowired
    private FleetCardAllocationRecoveryRecordService fleetCardAllocationRecoveryRecordService;

    @Override
    public List<FleetCardSubVo> selectFleetCardSubList(FleetCardSubQueryForm fleetCardSubQueryForm) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (SecurityUtils.isPartner()) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(user);
            if (itemIds != null){
                fleetCardSubQueryForm.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        } else {
            if(fleetCardSubQueryForm.getEnterpriseId()==null){
                fleetCardSubQueryForm.setEnterpriseId(SecurityUtils.getLoginUser().getUser().getEnterpriseId());
            }
        }
        return fleetCardSubMapper.selectFleetCardSubList(fleetCardSubQueryForm);
    }

    @Override
    public List<FleetCardSub> selectByFleetCardId(Long fleetCardId) {
        return fleetCardSubMapper.selectByFleetCardId(fleetCardId);
    }

    @Override
    public List<FleetCardSub> selectAllByFleetCardId(Long fleetCardId) {
        return fleetCardSubMapper.selectAllByFleetCardId(fleetCardId);
    }

    @Override
    public int updateFleetCardSub(FleetCardSub fleetCardSub) {
        return fleetCardSubMapper.updateFleetCardSub(fleetCardSub);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateFleetCardSub(Long id, FleetCardSubForm fleetCardSubForm) {
        FleetCardSub fleetCardSub = new FleetCardSub();
        fleetCardSub.setId(id);
        fleetCardSub.setName(fleetCardSubForm.getName());
        fleetCardSub.setUpdatedBy(SecurityUtils.getUsername());
        fleetCardSub.setTruckNumber(fleetCardSubForm.getTruckNumber());

        FleetCardSub fleetCardSubResult = fleetCardSubMapper.selectFleetCardSubById(id);
        if (null != fleetCardSubResult && null == fleetCardSubResult.getAppUserId()) {
            SysAppUserInfo sysAppUserInfo = new SysAppUserInfo();
            sysAppUserInfo.setUserId(fleetCardSubResult.getAppUserId());
            sysAppUserInfo.setTruckNumber(fleetCardSubForm.getTruckNumber());
            appUserInfoMapper.updateAppUserInfo(sysAppUserInfo);
        }

        return fleetCardSubMapper.updateFleetCardSub(fleetCardSub);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateAllocationAmount(BigDecimal allocationAmount, Long id) {
        FleetCardSub fleetCardSub = fleetCardSubMapper.selectFleetCardSubById(id);
        fleetCardSub.setBalance(fleetCardSub.getBalance().add(allocationAmount));
        fleetCardSub.setUpdatedBy(SecurityUtils.getUsername());
        fleetCardSub.setUpdatedTime(new Date());

        // 扣除主卡余额
        FleetCard fleetCard = fleetCardService.getById(fleetCardSub.getFleetCardId());
        if (ObjectUtils.notEqual(fleetCard.getSecondaryCardAllocationType(), FleetCard.USE_TYPE_ALLOCATION))
            throw new CustomException("请选择额度分配方式为手动分配子卡额度");

        if (fleetCard.getBalance().compareTo(allocationAmount) < 0)
            throw new CustomException("主卡额度不足");
        fleetCard.setBalance(fleetCard.getBalance().subtract(allocationAmount));
        fleetCard.setUpdatedBy(SecurityUtils.getUsername());
        fleetCard.setUpdatedTime(new Date());
        fleetCardService.updateFleetCard(fleetCard);

        //分配记录
        FleetCardAllocationRecoveryRecord fleetCardAllocationRecoveryRecord = new FleetCardAllocationRecoveryRecord();
        fleetCardAllocationRecoveryRecord.setFleetCardId(fleetCardSub.getFleetCardId());
        fleetCardAllocationRecoveryRecord.setFleetCardSubId(id);
        fleetCardAllocationRecoveryRecord.setAmount(allocationAmount);
        fleetCardAllocationRecoveryRecord.setType(FleetCardAllocationRecoveryRecord.ALLOCATION);
        fleetCardAllocationRecoveryRecord.setCreatedBy(SecurityUtils.getUsername());
        fleetCardAllocationRecoveryRecord.setUpdatedBy(SecurityUtils.getUsername());
        fleetCardAllocationRecoveryRecordService.insertFleetCardAllocationRecoveryRecord(fleetCardAllocationRecoveryRecord);

        return fleetCardSubMapper.updateFleetCardSub(fleetCardSub);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int recovery(Long id) {
        FleetCardSub fleetCardSub = fleetCardSubMapper.selectFleetCardSubById(id);
        FleetCard fleetCard = fleetCardService.getById(fleetCardSub.getFleetCardId());
        if(fleetCard!=null){
            if(fleetCard.getSecondaryCardAllocationType().equals(FleetCard.USE_TYPE_SHARE)){
                throw new CustomException("当前为共享主卡额度模式，无法回收");
            }else if(fleetCard.getSecondaryCardAllocationType().equals(FleetCard.NOT_SET)){
                throw new CustomException("未配置子卡额度");
            }
        }
        if (fleetCardSub.getBalance().compareTo(BigDecimal.ZERO) == 0){
            throw new CustomException("子卡余额已为0");
        }



        fleetCard.setBalance(fleetCard.getBalance().add(fleetCardSub.getBalance()));
        fleetCard.setUpdatedTime(new Date());
        fleetCard.setUpdatedBy(SecurityUtils.getUsername());
        fleetCardService.updateFleetCard(fleetCard);

        //回收记录
        FleetCardAllocationRecoveryRecord fleetCardAllocationRecoveryRecord = new FleetCardAllocationRecoveryRecord();
        fleetCardAllocationRecoveryRecord.setFleetCardId(fleetCardSub.getFleetCardId());
        fleetCardAllocationRecoveryRecord.setFleetCardSubId(id);
        fleetCardAllocationRecoveryRecord.setAmount(fleetCardSub.getBalance());
        fleetCardAllocationRecoveryRecord.setType(FleetCardAllocationRecoveryRecord.RECOVERY);
        fleetCardAllocationRecoveryRecord.setCreatedBy(SecurityUtils.getUsername());
        fleetCardAllocationRecoveryRecord.setUpdatedBy(SecurityUtils.getUsername());
        fleetCardAllocationRecoveryRecordService.insertFleetCardAllocationRecoveryRecord(fleetCardAllocationRecoveryRecord);

        fleetCardSub.setBalance(BigDecimal.ZERO);
        fleetCardSub.setUpdatedTime(new Date());
        fleetCardSub.setUpdatedBy(SecurityUtils.getUsername());
        return fleetCardSubMapper.updateFleetCardSub(fleetCardSub);
    }

    @Override
    public int review(Long id, Integer status) {
        FleetCardSub fleetCardSub = fleetCardSubMapper.selectFleetCardSubById(id);
        if (ObjectUtils.notEqual(fleetCardSub.getStatus(), FleetCardSub.WAIT_REVIEW))
            throw new CustomException("该子卡已审核！请勿重复操作");

        FleetCardSub newFleetCardSub = new FleetCardSub();
        newFleetCardSub.setId(id);
        newFleetCardSub.setStatus(status);
        newFleetCardSub.setUpdatedTime(new Date());
        newFleetCardSub.setUpdatedBy(SecurityUtils.getUsername());
        return fleetCardSubMapper.updateFleetCardSub(newFleetCardSub);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleted(List<Long> ids) {
        ids.forEach(id -> {
            FleetCardSub fleetCardSub = fleetCardSubMapper.selectFleetCardSubById(id);
            if (fleetCardSub.getBalance().compareTo(BigDecimal.ZERO) > 0)
                throw new CustomException("子卡存在额度，请先回收！");

            fleetCardSub.setDel(System.currentTimeMillis());
            fleetCardSub.setUpdatedBy(SecurityUtils.getUsername());
            fleetCardSub.setUpdatedTime(new Date());
            fleetCardSubMapper.updateFleetCardSub(fleetCardSub);
        });
        return 1;
    }

    @Override
    public List<FleetCardSub> query(FleetCardSub fleetCardSubQuery) {
        return fleetCardSubMapper.query(fleetCardSubQuery);
    }

    @Override
    public List<FleetCardSub> selectFleetCardSubByIdAndSecondary(Long id) {
        return fleetCardSubMapper.selectFleetCardSubByIdAndSecondary(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addFleetCardSub(FleetCardSubAddForm fleetCardSubAddForm) {
        if (!RegexUtils.isPhoneNum(fleetCardSubAddForm.getPhone())) {
            throw new CustomException("手机号格式错误！");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long enterpriseId = loginUser.getUser().getEnterpriseId();
        if (ObjectUtils.notEqual(loginUser.getUser().getUserLevel(), "1")) {
            throw new CustomException("请使用油企账号操作！");
        }
        FleetCard fleetCardp = fleetCardMapper.selectFleetCardByPhone(fleetCardSubAddForm.getPhone(),enterpriseId);
        if (null != fleetCardp) {
            throw new CustomException("该用户手机号已经创建了车队卡！");
        }

        List<FleetCardSub> fleetCardSubs = fleetCardSubMapper.selectFleetCardSubByPhone(fleetCardSubAddForm.getPhone(),enterpriseId);
        if (null != fleetCardSubs && fleetCardSubs.size() > 0) {
            throw new CustomException("该用户手机号已经创建了车队卡子卡！");
        }

        FleetCard fleetCard = fleetCardService.getById(fleetCardSubAddForm.getFleetCardId());
        if (null == fleetCard) {
            throw new CustomException("车队信息不存在！");
        }

//        List<FleetCardSub> fleetCardSubList = fleetCardSubMapper.selectByFleetCardId(fleetCardSubAddForm.getFleetCardId());
//        if (null != fleetCardSubList && fleetCardSubList.size() > 0) {
//            throw new CustomException("车队下已存在子卡信息！");
//        }

        Map<String, Object> params = new HashMap<>();
        params.put("mobilePhone", fleetCardSubAddForm.getPhone());
        params.put("stationId", enterpriseId);
        List<SysAppUserInfo> sysAppUserInfos = appUserInfoMapper.selectAppUserInfoByPhoneAndStationId(params);
        Long appUserId = null;
        if (null != sysAppUserInfos && sysAppUserInfos.size() > 0) {
            // 已经是会员
            appUserId = sysAppUserInfos.get(0).getUserId();
        }

        if (StringUtils.isNotBlank(fleetCardSubAddForm.getTruckNumber()) && null != appUserId) {
            SysAppUserInfo sysAppUserInfo = new SysAppUserInfo();
            sysAppUserInfo.setUserId(appUserId);
            sysAppUserInfo.setTruckNumber(fleetCardSubAddForm.getTruckNumber());
            appUserInfoMapper.updateAppUserInfo(sysAppUserInfo);
        }

        FleetCardSub fleetCardSub = new FleetCardSub();
        fleetCardSub.setEnterpriseId(enterpriseId);
        // 如果是null，后期用户从公众号注册成为会员，申请加入车队进行匹配绑定
        fleetCardSub.setAppUserId(appUserId);
        fleetCardSub.setCardNumber("102" + System.currentTimeMillis());
        fleetCardSub.setFleetCardId(fleetCard.getId());
        fleetCardSub.setName(fleetCardSubAddForm.getName());
        fleetCardSub.setStatus(2);
        fleetCardSub.setPhone(fleetCardSubAddForm.getPhone());
        fleetCardSub.setTruckNumber(fleetCardSubAddForm.getTruckNumber());
        fleetCardSub.setCreatedTime(new Date());
        fleetCardSub.setCreatedBy(SecurityUtils.getUsername());
        return fleetCardSubMapper.insertFleetCardSub(fleetCardSub);
    }
}
